"""
角色相关的 API 端点
"""
from typing import List
from fastapi import APIRouter, HTTPException, Query, Depends, status as status_module
from ....schemas.role import RoleCreate, RoleUpdate, RoleResponse, RoleListResponse
from ....schemas.response import BaseResponse
from ....crud.role import role_crud
from ....core.exceptions import UserNotFoundError
from ....api.deps import get_current_user
from ....models.user import User

router = APIRouter()


@router.post(
    "/",
    response_model=BaseResponse[RoleResponse],
    summary="创建角色",
    description="创建一个新的角色（需要管理员权限）"
)
async def create_role(
    role_data: RoleCreate,
    current_user: User = Depends(get_current_user)
):
    """
    创建角色
    """
    try:
        role = await role_crud.create_role(role_data)
        return BaseResponse[RoleResponse](
            code=200,
            message="角色创建成功",
            data=RoleResponse.model_validate(role)
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status_module.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建角色失败"
        )


@router.get(
    "/",
    response_model=BaseResponse[RoleListResponse],
    summary="获取角色列表",
    description="获取所有角色列表（需要管理员权限）"
)
async def get_roles(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=1000, description="返回的记录数"),
    current_user: User = Depends(get_current_user)
):
    """
    获取角色列表
    """
    try:
        roles = await role_crud.get_roles(skip=skip, limit=limit)
        total = await role_crud.get_roles_count()
        
        role_list = [RoleResponse.model_validate(role) for role in roles]
        
        return BaseResponse[RoleListResponse](
            code=200,
            message="获取角色列表成功",
            data=RoleListResponse(total=total, roles=role_list)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取角色列表失败: {str(e)}"
        )


@router.get(
    "/{role_id}",
    response_model=BaseResponse[RoleResponse],
    summary="获取角色信息",
    description="根据角色ID获取角色信息（需要管理员权限）"
)
async def get_role(
    role_id: str,
    current_user: User = Depends(get_current_user)
):
    """
    根据角色ID获取角色信息
    """
    try:
        role = await role_crud.get_role_by_id(role_id)
        return BaseResponse[RoleResponse](
            code=200,
            message="获取角色信息成功",
            data=RoleResponse.model_validate(role)
        )
    except UserNotFoundError as e:
        raise HTTPException(
            status_code=status_module.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取角色信息失败: {str(e)}"
        )


@router.put("/{role_id}",
            response_model=BaseResponse[RoleResponse],
            summary="更新角色信息",
            description="更新指定角色的信息（需要管理员权限）"
            )
async def update_role(
    role_id: str,
    role_data: RoleUpdate,
    current_user: User = Depends(get_current_user)
):
    """
    更新角色信息
    """
    try:
        role = await role_crud.update_role(role_id, role_data)
        return BaseResponse[RoleResponse](
            code=200,
            message="角色更新成功",
            data=RoleResponse.model_validate(role)
        )
    except UserNotFoundError as e:
        raise HTTPException(
            status_code=status_module.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status_module.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新角色失败"
        )


@router.delete(
    "/{role_id}",
    response_model=BaseResponse[str],
    summary="删除角色",
    description="删除指定角色（需要管理员权限）"
)
async def delete_role(
    role_id: str,
    current_user: User = Depends(get_current_user)
):
    """
    删除角色
    """
    try:
        await role_crud.delete_role(role_id)
        return BaseResponse[str](
            code=200,
            message="角色删除成功",
            data="角色已被成功删除"
        )
    except UserNotFoundError as e:
        raise HTTPException(
            status_code=status_module.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除角色失败"
        )